package com.gjzt.business.web.service;

import com.eastdigit.util.HttpUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eastdigit.servlet.ReqBean;
import com.eastdigit.system.model.BusinessException;
import com.eastdigit.system.model.SqlBuilder;
import com.eastdigit.system.service.BaseService;
import com.gjzt.business.media.service.MediaFileService;
import com.gjzt.business.utils.Constant;
import sun.security.provider.certpath.BuildStep;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class WebService extends BaseService {

    public JSONObject queryBusOrStop(ReqBean reqBean) {
        String queryType = reqBean.getInfo("queryType");
        String param = reqBean.getInfo("param");
        if (StringUtils.isBlank(queryType)) {
            throw new BusinessException("缺少参数!");
        }
        String sql = "";

        JSONObject returnData = new JSONObject();
        if (Constant.MEDIA_TYPE_BUS.equals(queryType)) { // 车辆
            sql = "select b.BUS_ID,b.VEHICLE_NO,b.PLATE_NO,b.LINE_NO,b.COMPANY_NAME FROM MEDIA_BUS b "
                    + "where  b.VEHICLE_NO = '" + param.split("/")[0] + "'";
            JSONArray array = query(sql);
            returnData = array.getJSONObject(0);
            if (returnData != null) {
                String resourceSql = "select r.*,t.MEDIA_NAME from MEDIA_RESOURCE r "
                        + "LEFT JOIN MEDIA_TYPE t ON t.MEDIA_ID = r.MEDIA_TYPE "
                        + "where r.STATUS <> '0' AND r.BUS_ID = '" + returnData.getString("busId") + "'";
                JSONArray resourceList = query(resourceSql);
                returnData.put("resourceList", resourceList);
            }

        } else if (Constant.MEDIA_TYPE_STOP.equals(queryType)) { // 站点
            String[] paramArr = param.split("/");
            String stopName = paramArr[0].trim();
            String roadName = paramArr[1].split("\\(")[0].trim();
            String direction = paramArr[1].split("\\(")[1].substring(paramArr[1].split("\\(")[1].indexOf(":") + 1,
                    paramArr[1].split("\\(")[1].length() - 1).trim();
            sql = "select s.STOP_ID, s.ROAD_NAME,s.DIRECTION,s.STOP_NAME FROM MEDIA_STOP s " + "where  s.STOP_NAME = '" + stopName
                    + "' and s.DIRECTION = '" + direction + "'" + " and s.ROAD_NAME = '" + roadName + "'";
            JSONArray array = query(sql);
            returnData = array.getJSONObject(0);
            if (returnData != null) {
                String resourceSql = "select r.*,t.MEDIA_NAME from MEDIA_RESOURCE r "
                        + "LEFT JOIN MEDIA_TYPE t ON t.MEDIA_ID = r.MEDIA_TYPE "
                        + "where r.STATUS <> '0' AND r.STOP_ID = '" + returnData.getString("stopId") + "'";
                JSONArray resourceList = query(resourceSql);
                returnData.put("resourceList", resourceList);
            }
        }
        return returnData;
    }

    public JSONObject resCheckQuery(ReqBean reqBean) {

        String queryType = reqBean.getInfo("queryType");
        String param = reqBean.getInfo("param");
        if (StringUtils.isBlank(queryType)) {
            throw new BusinessException("缺少参数!");
        }

        SqlBuilder sqlBuilder = new SqlBuilder("select r.*,b.VEHICLE_NO,b.PLATE_NO,b.LINE_NO,b.COMPANY_NAME,"
                + "s.ROAD_NAME,s.DIRECTION,s.STOP_NAME,t.MEDIA_NAME "
                + "FROM MEDIA_RESOURCE r LEFT JOIN MEDIA_BUS b ON b.BUS_ID = r.BUS_ID "
                + "LEFT JOIN MEDIA_STOP s ON s.STOP_ID = r.STOP_ID "
                + "LEFT JOIN MEDIA_TYPE t ON t.MEDIA_ID = r.MEDIA_TYPE where 1=1 ");

        if (Constant.MEDIA_TYPE_BUS.equals(queryType)) { // 车辆
            sqlBuilder.addWhere("b.VEHICLE_NO", param.split("/")[0]).orderBy("order by r.RESOURCE_ID DESC");
        } else if (Constant.MEDIA_TYPE_STOP.equals(queryType)) { // 站点
            String[] paramArr = param.split("/");
            String stopName = paramArr[0];
            String roadName = paramArr[1].split("\\(")[0];
            String direction = paramArr[1].split("\\(")[1].substring(paramArr[1].split("\\(")[1].indexOf(":") + 1,
                    paramArr[1].split("\\(")[1].length() - 1);
            sqlBuilder.addWhere("s.STOP_NAME", stopName).addWhere("s.ROAD_NAME", roadName)
                    .addWhere("s.DIRECTION", direction).orderBy("order by r.RESOURCE_ID DESC");
        }
        return queryTable(sqlBuilder, reqBean.getInfoInt("_pageSize"), reqBean.getInfoInt("_pageIndex"));
    }

    public JSONObject resCheckFuzzyQuery(ReqBean reqBean) {
        String queryType = reqBean.getInfo("queryType");
        String param = reqBean.getInfo("param");
        if (StringUtils.isBlank(queryType)) {
            throw new BusinessException("缺少参数!");
        }
        String sql = "";
        if (Constant.MEDIA_TYPE_BUS.equals(queryType)) { // 车辆
            sql = sql
                    + "SELECT CONCAT(b.VEHICLE_NO,' / ',b.PLATE_NO,' ( 线路:',b.LINE_NO,' )') showName FROM MEDIA_BUS b where 1=1 ";
            if (StringUtils.isNotBlank(param)) {
                sql += "and (b.VEHICLE_NO LIKE '%" + param + "%' or b.LINE_NO LIKE '%" + param
                        + "%' or b.PLATE_NO LIKE '%" + param + "%') order by b.BUS_ID DESC";
            }
        } else if (Constant.MEDIA_TYPE_STOP.equals(queryType)) { // 站点
            System.out.println(param);
            sql = sql
                    + "SELECT CONCAT(s.STOP_NAME,' / ',s.ROAD_NAME,' ( 行向:',s.DIRECTION,' )') showName FROM MEDIA_STOP s where 1=1 ";
            if (StringUtils.isNotBlank(param)) {
                sql += " and (s.STOP_NAME LIKE '%" + param + "%' or s.ROAD_NAME LIKE '%" + param
                        + "%' or s.DIRECTION LIKE '%" + param + "%') order by s.STOP_ID DESC";
            }
        }
        return queryTable(new SqlBuilder(sql), reqBean.getInfoInt("_pageSize"), reqBean.getInfoInt("_pageIndex"));
    }

    public JSONObject queryCurrentBillDetail(ReqBean reqBean) {
        String resourceId = reqBean.getInfo("resourceId");
        if (StringUtils.isBlank(resourceId)) {
            throw new BusinessException("缺少参数!");
        }

        String sql = "SELECT pbd.ID,pb.*,f.PATH,f.`NAME`,c.CUSTOMER_NAME,c.CONTACTS_PHONE,pmbd.MAKE_BILL_ID FROM AD_PUBLISH_BILL_DETAIL pbd "
                + "LEFT JOIN AD_PUBLISH_BILL pb ON pb.BILL_ID = pbd.BILL_ID "
                + "LEFT JOIN AD_CUSTOMER c ON c.CUSTOMER_ID = pb.CUSTOMER_ID "
                + "LEFT JOIN AD_PUBLISH_MAKE_BILL_DETAIL pmbd ON pmbd.PUBLISH_DETAIL_ID = pbd.ID "
                + "LEFT JOIN MEDIA_FILE f ON f.SOURCE_TYPE = '"
                + Constant.MEDIAFILE_SOURCE_TYPE_FINISHED
                + "' AND f.SOURCE_DATA_ID = pbd.ID AND "
                + "f.`STATUS` = '1' where pbd.RESOURCE_ID = '"
                + resourceId
                + "' ORDER BY DATEDIFF(SYSDATE(),pb.PUBLISH_OFF_TIME) ASC";
        JSONArray array = query(sql);
        JSONObject returnJson = new JSONObject();
        if (array != null && array.size() > 0) {
            returnJson = array.getJSONObject(0);
            String publishImgSql = "select f.`NAME`,f.PATH FROM MEDIA_FILE f where f.SOURCE_TYPE = '"
                    + Constant.MEDIAFILE_SOURCE_TYPE_PUBLISH_IMG + "' AND f.SOURCE_DATA_ID = '"
                    + returnJson.optString("billId") + "' AND f.`STATUS` = '1'";
            JSONArray publishImgs = query(publishImgSql);
            returnJson.put("publishImgs", publishImgs);
        }
        return returnJson;
    }

    public JSONObject changeOAuth(ReqBean reqBean, HttpServletRequest request) throws Exception {
        Map<String, String> parmMap = new HashMap<String, String>();
        Map<String, String[]> map = request.getParameterMap();
        Set<String> key = map.keySet();
        Iterator<String> iterator = key.iterator();
        while (iterator.hasNext()) {
            String k = iterator.next();
            parmMap.put(k, map.get(k)[0]);
        }

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String tempKey = (String) headerNames.nextElement();
            String value = request.getHeader(tempKey);
            if (tempKey.equals("access_token") || tempKey.equals("user_id")) {
                parmMap.put(tempKey, value);
            }
        }

        String url = request.getParameter("url");

        String str = HttpUtil.postWithUrlEncodedFormEntity(url, parmMap);
        System.out.println(str);
        JSONObject jsonObject = JSONObject.fromObject(str);
        if (StringUtils.isNoneBlank(jsonObject.optString("error"))) {
            throw new BusinessException("请求失败" + jsonObject.getString("error") + "!");
        } else if (StringUtils.isNoneBlank(jsonObject.optString("resCode"))
                && "0".equals(jsonObject.optString("resCode"))) {
            throw new BusinessException("请求失败!" + jsonObject.getString("resCode") + ":"
                    + jsonObject.getString("resDesc"));
        }
        return jsonObject;

    }
}
